package com.kun.peng.system.service.impl;

import com.kun.peng.exception.EntityNotFoundException;
import com.kun.peng.security.service.UserCacheClean;
import com.kun.peng.system.domain.User;
import com.kun.peng.system.service.mapstruct.UserMapStruct;
import com.kun.peng.mybatis.base.IBaseService;
import com.kun.peng.system.mapper.UserMapper;
import com.kun.peng.system.service.UserService;
import com.kun.peng.system.service.dto.UserDto;
import com.kun.peng.system.service.dto.UserQueryCriteria;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * Created on 2021/11/19.
 *
 * @author xuebaopeng
 * Description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl  extends IBaseService<UserMapper, User> implements UserService {
    private final UserMapStruct userMapStruct;
    private final UserCacheClean userCacheClean;
    @Override
    public List<User> findByMenuId(Long id) {
        return getBaseMapper().findByMenuId(id);
    }

    @Override
    public List<User> findByRoleId(Long roleId) {
        return getBaseMapper().findByRoleId(roleId);
    }

    /**
     * 根据角色中的部门查询
     * @param deptId
     * @return
     */
    @Override
    public List<User> findByRoleDeptId(Long deptId) {
        return getBaseMapper().findByRoleDeptId(deptId);
    }

    @Override
    public UserDto
    findByName(String userName) {
        User user = getBaseMapper().findByUsername(userName);
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", userName);
        } else {
            return userMapStruct.toDto(user);
        }
    }

    @Override
    public void updatePass(String username, String encryptPassword) {
        getBaseMapper().updatePass(username, encryptPassword, new Date());
        flushCache(username);
    }

    @Override
    public Object queryAll(UserQueryCriteria criteria, Pageable pageable) {
        return null;
    }

    @Override
    public int countByDepts(Set<Long> deptIds) {
        return getBaseMapper().countByDepts(deptIds);
    }

    /**
     * 清理 登陆时 用户缓存信息
     *
     * @param username /
     */
    private void flushCache(String username) {
        userCacheClean.cleanUserCache(username);
    }
}
